package top.xianggg.xservers.shiro.configuration;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import top.xianggg.xservers.common.spring.SpringContextHolder;
import top.xianggg.xservers.sys.entity.SysPermission;
import top.xianggg.xservers.sys.entity.SysRole;
import top.xianggg.xservers.sys.entity.SysUser;
import top.xianggg.xservers.sys.repository.SysUserRepository;

import java.util.Optional;

/**
 * @author Xiang
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
        //获取用户的输入的账号.
        String username = (String)token.getPrincipal();
        System.out.println(token.getCredentials());
        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        Optional<SysUser> user = SpringContextHolder.getBean(SysUserRepository.class).findByUsername(username);
        if(user.isPresent()){
            return new SimpleAuthenticationInfo(
                    user,
                    user.get().getPassword(),
                    ByteSource.Util.bytes(user.get().getSalt()),
                    getName()
            );
        }else {
            throw new AuthenticationException("不存在的用户");
        }
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        SysUser userInfo  = (SysUser)principalCollection.getPrimaryPrincipal();
        for(SysRole role:userInfo.getRoleList()){
            authorizationInfo.addRole(role.getRole());
            for(SysPermission p:role.getPermissions()){
                authorizationInfo.addStringPermission(p.getPermission());
            }
        }
        return authorizationInfo;
    }
}
